package com.sam.im.heiqun.uis.activities;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sam.im.heiqun.utils.PictureUtil;
import com.sam.im.heiqun.widgets.imagepicker.PhotoPickerActivity;
import com.sam.im.heiqun.widgets.imagepicker.SelectModel;
import com.sam.im.heiqun.widgets.imagepicker.intent.PhotoPickerIntent;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.ImageEntity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.SendCircleAdapter;
import com.sam.im.heiqun.uis.beans.ReportResultBean;
import com.sam.im.heiqun.utils.BitmapUtils;
import com.sam.im.heiqun.utils.HttpAssist;
import com.sam.im.heiqun.utils.ImageCheckoutUtil;
import com.sam.im.heiqun.utils.PersimmionsUtils;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.EventBusType;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wangguodong on 2017/9/12.
 */

public class ComplaintEvidenceActivity extends BaseSwipeBackActivity {
    private static final int CHOSE_PICS = 1111;
    private static final int IMAGE_SIZE = 300 * 1024;

    @BindView(R.id.grid_imag)
    GridView mGridView ;
    @BindView(R.id.txt_commit)
    TextView txt_commit ;
    @BindView(R.id.txt_right_content)
    TextView txt_right_content ;
    @BindView(R.id.relative_session)
    RelativeLayout relative_session ;

    private SendCircleAdapter adapter;
    private List<Bitmap> photodatas = new ArrayList<>();
    private List<File> files = new ArrayList<>();

    private PersimmionsUtils persimmionsUtils ;
    boolean isgo = false ;
    boolean isGone = false ;

    private String uid = "" ;//
    private int isGroup = 1 ;//

    private String select ;
    private int selectNum ;
    private ImageEntity upload;

    public static void start(Activity activity, String uid, int isGroup){
        Intent intent = new Intent(activity, ComplaintEvidenceActivity.class);
        intent.putExtra("uid", uid);
        intent.putExtra("isGroup", isGroup);
        activity.startActivity(intent);
    }

    @Override
    protected String getTitleText() {
        return getResources().getString(R.string.complaint);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        isGroup = getIntent().getIntExtra("isGroup",1);
        uid = getIntent().getStringExtra("uid");
        initPersimmions();

        // 设置默认图片为加号
        Bitmap bp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_addpic);
        photodatas.add(bp);

        adapter = new SendCircleAdapter(getApplicationContext(), photodatas, mGridView);
        mGridView.setAdapter(adapter);

        // 设置点击监听事件
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (photodatas.size() == 10) {
                    Toast.makeText(ComplaintEvidenceActivity.this, getResources().getString(R.string.image_man_9), Toast.LENGTH_SHORT).show();
                } else {
                    if (position == photodatas.size() - 1 && !isGone) {
                        isgo = false ;
//                        getPersimmions();
                        persimmionsUtils.getPersimmions(1,new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE});
                    } else {
                        ToolsUtils.showToast(ComplaintEvidenceActivity.this, getResources().getString(R.string.long_an_delete));
                        //Toast.makeText(SendCircleActivity.this, "长按可选择删除", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        // 设置长按事件
        mGridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                dialog(position);
                return true;
            }
        });

    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_complaint_evidence;
    }

    /*
     * Dialog对话框提示用户删除操作 position为删除图片位置
	 */
    protected void dialog(final int position) {
        if (position == photodatas.size()) {
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(ComplaintEvidenceActivity.this);
        builder.setMessage(getResources().getString(R.string.delete_image_ok));
        builder.setTitle(getResources().getString(R.string.tip));
        builder.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                photodatas.remove(position);
                files.remove(position);

                if (isGone){
                    isGone = false ;
                    Bitmap bp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_addpic);
                    photodatas.add(bp);
                }

                adapter.notifyDataSetChanged();
            }
        });
        builder.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case CHOSE_PICS:
                if (data != null) {
                    ArrayList<String> stringArrayListExtra = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    if (stringArrayListExtra.size() > 0) {
                        for (int i = 0; i < stringArrayListExtra.size(); i++) {
                            String imgpath = stringArrayListExtra.get(i);
                            Log.i("info","选择的图片路劲=="+imgpath);
                           // Bitmap bitmap= PictureUtil.compressImage(imgpath);
                            try {
//              Bitmap bitmap = PictureUtil.getBitmapFormUri(this, uri);
                           /* Bitmap bitmap = PictureUtil.getSmallBitmap(imgpath);
                            if (bitmap == null) {
                                assert imgpath != null;
                                mCurrentPhotoFile = new File(imgpath); // 图片文件路径
                            } else {
                                mCurrentPhotoFile = PictureUtil.bitmapToFileJPG(bitmap, imgpath);
                            }*/
                                File getfile = new File(imgpath);
                                // mCurrentPhotoFile = new File(imgpath);
                                // assert mCurrentPhotoFile != null;
                                if (getfile.exists()) {
                                    int size = ImageCheckoutUtil.getImageSize(ImageCheckoutUtil.getLoacalBitmap(imgpath));
                                    float s = size / 8.0f / 1024;
                                    if (s > IMAGE_SIZE) {
                                        Log.i("info", "图片尺寸太大");
                                    } else {//这里处理返回的路径
                                        files.add(getfile);
                                        //sendImage(mCurrentPhotoFile);
                                        Bitmap newBp = BitmapUtils.decodeSampledBitmapFromFd(getfile.getPath(), 300, 300);
                                        photodatas.remove(photodatas.size() - 1);
                                        Bitmap bp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_addpic);
                                        photodatas.add(newBp);
                                        if (null!=photodatas && photodatas.size()<9){
                                            isGone = false ;
                                            photodatas.add(bp);
                                        }else isGone = true;

                                        adapter.notifyDataSetChanged();
                                    }
                                } else {
                                    showToast(getResources().getString(R.string.this_file_nonentity));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            //files.add(new File(imgpath));

                        }
                    }
                }
                break;
            case ChatHistoryEvidenceActivity.RESULT_HISTORY_EVIDENCE :
                if (resultCode == 10){
                    selectNum = data.getIntExtra("selectNum", 0);
                    select = data.getStringExtra("select");
                    txt_right_content.setText(selectNum + getResources().getString(R.string.jilu_geshu));
                }
                break;
        }
    }

    /**
     * 初始化权限管理
     */
    private void initPersimmions(){
        persimmionsUtils = new PersimmionsUtils(ComplaintEvidenceActivity.this, new PersimmionsUtils.PersimmionsListener() {
            @Override
            public void OnPersimmionsSuccess(int type) {
                switch (type){
                    case 1 :
                        if (!isgo){
                            PhotoPickerIntent photointent = new PhotoPickerIntent(ComplaintEvidenceActivity.this);
                            photointent.setSelectModel(SelectModel.MULTI);
                            photointent.setShowCarema(true); // 是否显示拍照， 默认false
                            photointent.setMaxTotal(9 - photodatas.size() + 1); // 最多选择照片数量，默认为9
                            //photointent.setImageConfig(conFig);
                            startActivityForResult(photointent, CHOSE_PICS);
                        }
                        isgo = true ;
                        break;
                }
            }

            @Override
            public void OnPersimmionsFail(int type, int pos, String persimmion) {
                showToast(getResources().getString(R.string.no_pawr_nouse));
            }
        });
    }

    @OnClick({R.id.txt_commit, R.id.relative_session})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.pre_v_back:
                finish();
                break;
            case R.id.txt_commit:

                if (selectNum <= 0){
                    showToast(getResources().getString(R.string.must_commit_jilu));
                    return;
                }

                if (files.size() > 0) {
                    showProgress(getResources().getString(R.string.commit_now),false);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            // Looper.loop();
                            upload = HttpAssist.upload(files);
                            StringBuffer sb = new StringBuffer("");
                            if (upload == null) {
                                Log.i("info", "图片上传失败");
                                hideProgress();
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        showToast("图片上传失败");
                                    }
                                });

                            } else {
                                List<String> info = upload.getData().getInfo();
                                for (int q = 0; q < info.size(); q++) {
                                    sb.append(info.get(q));
                                    if (info.size() > 1 && q != info.size() - 1) {
                                        sb.append(",");
                                    }
                                }
                                report(sb.toString());
                            }
                        }
                    }).start();
                }else {
                    report("");
                }

                break;
            case R.id.relative_session:
                ChatHistoryEvidenceActivity.start(ComplaintEvidenceActivity.this,uid,isGroup);
                break;
        }
    }

    private void report(String imags) {
        Log.i("=====", "report: ======uid="+uid);
        PGService.getInstance().report(ToolsUtils.getMyUserId(), uid, ""+isGroup, imags, select
        ).subscribe(new AbsAPICallback<ReportResultBean>() {
            @Override
            protected void onResultError(ApiException ex) {
                //showToast(getResources().getString(R.string.commit_fail));
                String displayMessage = ex.getDisplayMessage();
                try {
                    JSONObject object = new JSONObject(displayMessage);
                    String data = object.getString("data");
                    showToast(data);
                    hideProgress();
                    EventBus.getDefault().post(EventBusType.RESULT_REPORT_SUCCESS);
                    finish();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNext(ReportResultBean sendCircleEntivity) {
                showToast(getResources().getString(R.string.commit_success));
                hideProgress();
                EventBus.getDefault().post(EventBusType.RESULT_REPORT_SUCCESS);
                finish();
            }
        });
    }

}
